import _ from "lodash";

export function handleBack() {
  let pages = getCurrentPages();
  if (+pages.length === 1) {
    uni.navigateTo({ url: "/pages/login/index" });
  } else {
    uni.navigateBack({ delta: 1 });
  }
}

export function paramsToQuerystring(params: { [key: string]: any }) {
  let entries = _.entries(params);
  let query = _.chain(entries)
    .map((arr) => {
      return arr[0] + "=" + arr[1];
    })
    .value()
    .join("&");
  return query;
}

export async function showConfirmModal(title = "", content = "") {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      success({ confirm }) {
        resolve(confirm);
      },
      fail() {
        resolve(false);
      },
    });
  });
}

export async function showToast(title = "", duration = 1500) {
  return new Promise((resolve) => {
    uni.showToast({
      title,
      icon: "none",
      duration,
      success() {
        resolve(true);
      },
      fail() {
        resolve(false);
      },
    });
  });
}

export function copyData(str: string) {
  uni.setClipboardData({
    data: str,
    success() {
      uni.showToast({
        icon: "none",
        title: "已复制内容到剪切板",
      });
    },
  });
}

export function makePhoneCall(phoneNumber: string) {
  uni.makePhoneCall({
    phoneNumber,
  });
}

export function previewImage({ imgList, url }) {
  uni.previewImage({
    urls: imgList,
    current: url,
  });
}

export async function scanCode(msg: string) {
  return new Promise((resovle, reject) => {
    uni.scanCode({
      //扫描API
      success(res) {
        //扫描成功
        if (_.includes(_.get(res, "errMsg"), "ok")) {
          let result = _.get(res, "result");
          resovle(result);
        } else {
          reject("");
          showToast(msg);
        }
      },
      fail() {
        reject("");
        showToast(msg);
      },
    });
  });
}
